package com.scbo.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.scbo.DTO.Buildorder;
import com.scbo.DTO.ItemBO;
import com.scbo.database.ScboDAO;
import com.scbo.main.R;
import com.scbo.utility.BuildOrderArrayAdapter;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class DownloadActivity extends Activity {
	public static String URL_DOMAIN = "http://192.168.1.101:8080/";
	public static String URL_GETALLBO = URL_DOMAIN + "ScboServer/rest/BO/getAll";
	public static String URL_GETITEMS = URL_DOMAIN + "ScboServer/rest/BO/getByID?id=";
	
	ListView itemsListView;
	ArrayList<Buildorder> listItems = null;
	BuildOrderArrayAdapter adapter = null;
	Buildorder downloadedBuildOrder = null;
	private ScboDAO datasource;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_download);
		itemsListView = (ListView) findViewById(R.id.lvBuildOrderDownload);
		listItems = new ArrayList<Buildorder>();

		adapter = new BuildOrderArrayAdapter(this, listItems);
		itemsListView.setAdapter(adapter);
		datasource = new ScboDAO(this);
		datasource.open();
		new HttpGetTask().execute(URL_GETALLBO);
		itemsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				Buildorder buildOrder = (Buildorder) parent.getItemAtPosition(position);
				
				String url = URL_GETITEMS + buildOrder.getId(); 
				Log.d("KHANHVQ", "url = " + url);
				downloadedBuildOrder = datasource.createBuildOrderReturnObj(buildOrder);
				Log.d("KHANHVQ", "downloaded ID = " + downloadedBuildOrder.getId());
				new DownloadBuildTask().execute(url);
			}
		});
	}

	private class HttpGetTask extends AsyncTask<String, String, String> {
		HttpClient httpclient;
		HttpGet request;
		private ProgressDialog Dialog = new ProgressDialog(DownloadActivity.this);

		protected void onPreExecute() {
			httpclient = new DefaultHttpClient();
			Dialog.setMessage("Please wait..");
			Dialog.show();
		}

		// Call after onPreExecute method
		protected String doInBackground(String... urls) {
			String jaxrsmessage = "aaaa";
			String url = urls[0];
			Log.d("KHANHVQ", url);
			request = new HttpGet(url);
//			request.addHeader("Accept", "application/json");
			request.addHeader("Accept", "text/plain");
			try {
				HttpResponse response = httpclient.execute(request);
				HttpEntity entity = response.getEntity();
				InputStream instream = entity.getContent();
				jaxrsmessage = read(instream);
			}

			catch (Exception e) {
				e.printStackTrace();
			}

			return jaxrsmessage;
		}

		protected void onPostExecute(String unused) {
			Dialog.dismiss();
			Gson gson = new Gson();
//			List list = new ArrayList();
//			Type listType = new TypeToken<Collection<Itembo>>() {
//			}.getType();
//			list = gson.fromJson(unused, listType);
			
			Log.d("KHANHVQ", unused);
			List<Buildorder> postsList = Arrays.asList(gson.fromJson(unused,
					Buildorder[].class));
			if (postsList != null) {
				for (int i = 0; i < postsList.size(); i++) {
					listItems.add(postsList.get(i));
					Log.d("KHANHVQ", "text = " + postsList.get(i).getName());
				}
			}
			adapter.notifyDataSetChanged();
			// Itembo item = (Itembo) list.get(0);
			// txtjsonParsed.setText("name" + item.getText());
		}
	}
	
	
	private class DownloadBuildTask extends AsyncTask<String, String, String> {
		HttpClient httpclient;
		HttpGet request;
		private ProgressDialog Dialog = new ProgressDialog(DownloadActivity.this);

		protected void onPreExecute() {
			httpclient = new DefaultHttpClient();
			Dialog.setMessage("Downloading..");
			Dialog.show();
		}

		// Call after onPreExecute method
		protected String doInBackground(String... urls) {
			String jaxrsmessage = "aaaa";
			String url = urls[0];
			Log.d("KHANHVQ", url);
			request = new HttpGet(url);
//			request.addHeader("Accept", "application/json");
			request.addHeader("Accept", "text/plain");
			try {
				HttpResponse response = httpclient.execute(request);
				HttpEntity entity = response.getEntity();
				InputStream instream = entity.getContent();
				jaxrsmessage = read(instream);
			}

			catch (Exception e) {
				e.printStackTrace();
			}

			return jaxrsmessage;
		}

		protected void onPostExecute(String unused) {
			Dialog.dismiss();
			Gson gson = new Gson();
			
			Log.d("KHANHVQ", unused);
			List<ItemBO> postsList = Arrays.asList(gson.fromJson(unused,
					ItemBO[].class));
			if (postsList != null) {
				for (int i = 0; i < postsList.size(); i++) {
					ItemBO item = postsList.get(i);
					item.setBuildOrder(downloadedBuildOrder);
					datasource.createItemBO(item);
				}
			}
			Toast.makeText(DownloadActivity.this, "Build Order is downloaded", Toast.LENGTH_LONG)
			.show();
		}
	}
	private static String read(InputStream instream) {
		StringBuilder sb = null;
		try {
			sb = new StringBuilder();
			BufferedReader r = new BufferedReader(new InputStreamReader(
					instream));
			for (String line = r.readLine(); line != null; line = r.readLine()) {
				sb.append(line);
			}

			instream.close();

		} catch (IOException e) {
		}
		return sb.toString();

	}
	@Override
	protected void onResume() {
		datasource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		datasource.close();
		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.download, menu);
		return true;
	}

}
